package com.libra.assemble.web.controller.other;

import com.libra.assemble.xutil.Constants;
import com.libra.assemble.xutil.FileContentType;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;


/**
 * 文件下载相关处理的业务代理.
 * 
 * @author Libra
 */
@Controller
@RequestMapping(value = "/download")
public class DownloadController {
	
	private static Logger logger= LoggerFactory.getLogger(DownloadController.class);
	
	/**
	 * 按2007以上版本的Excel下载指定文件.
	 * @param fileName
	 * @param response
	 */
	@RequestMapping(value = "excel")
	public void excel(@RequestParam(value = "fileName") String fileName, HttpServletResponse response) {
		try{
			String filePath = Constants.WEBROOT+"/static/files/excel/"+fileName;
			logger.info("WEBROOT:{} ; fileName:{} ;",filePath,fileName);
			File file = new File(filePath);
			logger.info("file.exists:{} ;",file.exists());
			
			if(file.exists()){
				fileName = URLEncoder.encode(fileName, "UTF-8");  
				response.reset();  
				response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
				response.addHeader("Content-Length", "" + file.length());  
				response.setContentType(FileContentType.xlsx);  
				OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
				outputStream.write(FileUtils.readFileToByteArray(file));  
				outputStream.flush();  
				outputStream.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		} 
	}
	
	
}
